package com.paradise.ytj.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Camera;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.paradise.ytj.R;
import com.paradise.ytj.bean.CloseEvent;
import com.paradise.ytj.bean.Constant;
import com.paradise.ytj.bean.OpenEvent;
import com.paradise.ytj.utils.CameraUtils;
import com.paradise.ytj.utils.RestartAPPTool;
import com.paradise.ytj.utils.SpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import static android.content.Context.AUDIO_SERVICE;
import static android.content.Context.USB_SERVICE;

/**
 * Created by Administrator on 2017/8/19 0019.
 * 本地预览界面
 */

public class LocationVideoFragment extends Fragment {

    private View inflate;
    private SurfaceView svLocation;
    private SurfaceHolder mSurfaceHolder;
    public static boolean isStart = true;
    public static boolean isCloseScreen = false;
    private TextView tvHour;
    private TextView tvYear;
    private TextView tvWeek;
    private Activity context;
    private int number_camera = 0;
    //在主线程里面处理消息并更新UI界面
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    long sysTime = System.currentTimeMillis();//获取系统时间
                    CharSequence sysTimeStr = DateFormat.format("HH:mm", sysTime);//时间显示格式
                    tvHour.setText(sysTimeStr); //更新时间

                    Date date = new Date();
                    CharSequence year = DateFormat.format("yyyy-MM-dd", date);
                    tvYear.setText(year);

                    Calendar calendar = Calendar.getInstance();
                    String mWay = calendar.get(Calendar.DAY_OF_WEEK) + "";
                    if ("1".equals(mWay)) {
                        tvWeek.setText(R.string.monday);
                    } else if ("2".equals(mWay)) {
                        tvWeek.setText(R.string.tuesday);
                    } else if ("3".equals(mWay)) {
                        tvWeek.setText(R.string.wednesday);
                    } else if ("4".equals(mWay)) {
                        tvWeek.setText(R.string.thursday);
                    } else if ("5".equals(mWay)) {
                        tvWeek.setText(R.string.friday);
                    } else if ("6".equals(mWay)) {
                        tvWeek.setText(R.string.saturday);
                    } else if ("7".equals(mWay)) {
                        tvWeek.setText(R.string.sunday);
                    }
                    break;
                default:
                    break;

            }
        }
    };
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        context = getActivity();
        inflate = View.inflate(context, R.layout.fragment_location_video, null);
        initView();
        initData();
        return inflate;
    }

    private void initView() {
        svLocation = (SurfaceView) inflate.findViewById(R.id.sv);
        tvHour = (TextView) inflate.findViewById(R.id.tv_hour);
        tvYear = (TextView) inflate.findViewById(R.id.tv_year);
        tvWeek = (TextView) inflate.findViewById(R.id.week);
        EventBus.getDefault().register(this);

    }

    private void initData() {
        new TimeThread().start(); //启动新的线程
    }

    @Override
    public void onResume() {
        super.onResume();
        int frag = SpUtils.getInt(context, Constant.BACKGROUND_NAME, Constant.BACKGROUND_DEFAULT);
        if (frag == 1) {
            mSurfaceHolder = svLocation.getHolder();
            mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
                @Override
                public void surfaceCreated(final SurfaceHolder surfaceHolder) {
                    if (CameraUtils.hasCamera()) {
                        number_camera = CameraUtils.getNumber();
                        Camera camera = CameraUtils.getCameraInstance();
                        if (camera != null) {
                            CameraUtils.startCamera(surfaceHolder);
                        } else {
                        }
                    } else {
                        number_camera = 0;
                        Toast.makeText(context, R.string.no_camera_hint, Toast.LENGTH_SHORT).show();
                        svLocation.setVisibility(View.GONE);
                    }
                }

                @Override
                public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
                }

                @Override
                public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
                    CameraUtils.stopCamera();
                }

            });
        } else {
            svLocation.setVisibility(View.GONE);
        }

        IntentFilter usbFilter = new IntentFilter();
        usbFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        usbFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        context.registerReceiver(mUsbReceiver, usbFilter);
    }

    class TimeThread extends Thread {

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = 1;  //消息(一个整型值)
                    mHandler.sendMessage(msg);// 每隔1秒发送一个msg给mHandler
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.POSTING)
    public void getOpen(OpenEvent openEvent) {
        if (isCloseScreen) {
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    svLocation.setVisibility(View.VISIBLE);
                }
            });
            isCloseScreen = false;
            int frag = SpUtils.getInt(context, Constant.BACKGROUND_NAME, Constant.BACKGROUND_DEFAULT);
            if (frag == 1) {
                mSurfaceHolder = svLocation.getHolder();
                mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
                    @Override
                    public void surfaceCreated(final SurfaceHolder surfaceHolder) {
                        if (CameraUtils.hasCamera()) {
                            Camera camera = CameraUtils.getCameraInstance();
                            if (camera != null) {
                                CameraUtils.startCamera(surfaceHolder);
                            }
                        } else {
                            Toast.makeText(context, R.string.no_camera_hint, Toast.LENGTH_SHORT).show();
                            svLocation.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
                    }

                    @Override
                    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
                        CameraUtils.stopCamera();
                    }

                });
            } else {
                svLocation.setVisibility(View.GONE);
            }
        }

    }


    @Subscribe(threadMode = ThreadMode.POSTING)
    public void getClose(CloseEvent closeEvent) {
        isCloseScreen = true;
        CameraUtils.stopCamera();
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                svLocation.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isStart = false;
        context.unregisterReceiver(mUsbReceiver);
        EventBus.getDefault().unregister(this);
    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                for (int i = 0; i < device.getInterfaceCount(); i++) {
                    if (device.getInterface(i).getInterfaceClass() == 14) {
                        if (number_camera == 0) {
                            RestartAPPTool.restartAPP(context);
                        } else if (number_camera >= 1) {
                            number_camera++;
                        }
                    }
                    if (device.getInterface(i).getInterfaceClass() == 1) {
                        RestartAPPTool.restartAPP(context);
                    }
                }
            } else {
                UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                for (int i = 0; i < device.getInterfaceCount(); i++) {
                    if (device.getInterface(i).getInterfaceClass() == 14) {
                        number_camera--;
                        break;
                    }
                }
                if (CameraUtils.getNumber() == 0) {
                    Toast.makeText(context, R.string.no_camera_hint, Toast.LENGTH_SHORT).show();
                    svLocation.setVisibility(View.GONE);
                }
            }
        }
    };

}
